<template>
  <Box>
    <h2 style="margin: 10px 15px" slot="title">物资信息</h2>
    <div slot="box">
      <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item ref="name" label="所属区域" prop="region">
          <a-select v-model="form.region" placeholder="请选择所属区域">
            <a-select-option v-for="(item, index) of this.diqu" :value="item.name" :key="index">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item ref="name" label="详细地址" prop="storageLocation">
          <!--          <a-input v-model="form.storageLocation" placeholder="请输入"/>-->
          <a-select v-model="form.storageLocation" :show-search="true" :allowClear="false"
            :default-active-first-option="false" :show-arrow="false" :filter-option="false" :not-found-content="null"
            style="width: 100%" placeholder="请输入详细地址" @search="onSearch" @change="onChange">
            <a-select-option v-for="(item, key) in positionList" :key="key" :value="item">{{
              item.address
            }}</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item ref="name" label="经纬度" prop="longitude">
          <a-input v-model="form.longitude" placeholder="经度" style="width: 49%" />
          <a-input v-model="form.latitude" placeholder="纬度" style="width: 49%; margin-left:6px;" />
        </a-form-model-item>
        <a-form-model-item ref="name" label="联系方式" prop="contactInformation">
          <a-input v-model="form.contactInformation" placeholder="请输入联系方式" />
        </a-form-model-item>
        <div class="list" style="display: flex">
          <a-form-model-item ref="name" label="物资基础信息" prop="a">
            <div style="width: 100%;">
              <a-table :columns="columns" :data-source="data" bordered>
                <template slot="materialName" slot-scope="text, record">
                  <div key="materialName">
                    <a-input v-if="record.editable" style="margin: -5px 0" :value="text" placeholder="请输入物资名称"
                      @change="e => handleChange(e.target.value, record.id, 'materialName')" />
                    <template v-else>
                      {{ text }}
                    </template>
                  </div>
                </template>
                <template slot="materialBrand" slot-scope="text, record">
                  <div key="materialBrand">
                    <a-input v-if="record.editable" style="margin: -5px 0" :value="text" placeholder="请输入物资品牌"
                      @change="e => handleChange(e.target.value, record.id, 'materialBrand')" />
                    <template v-else>
                      {{ text }}
                    </template>
                  </div>
                </template>
                <template slot="stock" slot-scope="text, record">
                  <div key="stock">
                    <a-input-number :min="0" v-if="record.editable" placeholder="请输入库存" style="margin: -5px 0;width: 100%"
                      :value="text" @change="e => handleChange(e, record.id, 'stock')" />
                    <template v-else>
                      {{ text }}
                    </template>
                  </div>
                </template>
                <template slot="unit" slot-scope="text, record">
                  <div key="unit">
                    <a-select placeholder="请选择单位" v-if="record.editable" style="margin: -5px 0" :value="text"
                      @change="e => handleChange(e, record.id, 'unit')">
                      <a-select-option v-for="(item, index) of filterMultiDictText1('wuzitop', '')" :value="item.text"
                        :key="index">
                        {{ item.text }}
                      </a-select-option>
                    </a-select>

                    <template v-else>
                      {{ text }}
                    </template>
                  </div>
                </template>

                <template slot="operation" slot-scope="text, record">
                  <div class="editable-row-operations">
                    <span v-if="record.editable">
                      <a @click="() => save(record.id)">保存</a>
                      <a-popconfirm title="取消保存?" @confirm="() => cancel(record.id)">
                        <a>取消</a>
                      </a-popconfirm>
                    </span>
                    <span v-else>
                      <a @click="() => edit(record.id)">编辑</a>
                      <a-popconfirm title="确定要删除所编辑的内容?" @confirm="() => onDelete(record.id)">
                        <a href="javascript:;">删除</a>
                      </a-popconfirm>
                    </span>
                  </div>
                </template>
                <template slot="footer">
                  <a href="javascript:;" @click="handleAdd"> + 添加</a>
                </template>
              </a-table>
            </div>
            <a-form-model-item style="display: flex">
              <a-button type="primary" @click="query">
                确定
              </a-button>
              <a-button style="margin-left: 10px;" @click="uploads">
                取消
              </a-button>
            </a-form-model-item>
          </a-form-model-item>
        </div>
      </a-form-model>
      <Map ref="mapDrawId" @pisitionList="onPisitionList" />
      <div>
        <a-modal v-model="visible" title="再次确认" @ok="handleOk">
          <div>您确定要修改此数据</div>
        </a-modal>
      </div>
    </div>
  </Box>
</template>

<script>
import Box from '@/views/xlgc/Box/index'
import { getDictItemsFromCache } from '@api/api'
import { getfrom } from '@api/xlgc/lawCase'
import { detailsList, getInformation, resCreate, topXiangping, updateWz } from '@api/xlgc/Res'
import Map from '@/views/xlgc/modules/map'
export default {
  name: 'AddRes',
  components: { Box, Map },
  data() {
    return {
      positionList: [],
      data: [],
      oldData: [],
      columns: [
        {
          title: '序号',
          dataIndex: 'index',
          width: 60,
          align: 'center',
          customRender: (text, record, index) =>
            `${(this.pageFilter.pageNo - 1) * this.pageFilter.pageSize + (index + 1)}` // 序号分页后连续
        },
        {
          title: '物质名称',
          dataIndex: 'materialName',
          width: '18%',
          scopedSlots: { customRender: 'materialName' }
        },
        {
          title: '物资品牌',
          dataIndex: 'materialBrand',
          width: '18%',
          scopedSlots: { customRender: 'materialBrand' }
        },
        {
          title: '单位',
          dataIndex: 'unit',
          width: '18%',
          scopedSlots: { customRender: 'unit' }
        },
        {
          title: '库存',
          dataIndex: 'stock',
          width: '18%',
          scopedSlots: { customRender: 'stock' }
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: '18%',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      editingKey: '',
      visible: false,
      fileList: [],
      labelCol: { span: 2 },
      wrapperCol: { span: 6 },
      diqu: {},
      other: '',
      pageFilter: {
        pageNo: 1,
        pageSize: 10
      },
      form: {
        latitude: '',
        longitude: '',
        id: undefined,
        region: undefined,
        storageLocation: undefined,
        contactInformation: ''
      },
      count: 1,
      rules: {
        region: [{ required: true, message: '请输入所属区域', trigger: 'blur' }],
        storageLocation: [{ required: true, message: '请输入发生地详址', trigger: 'blur' }],
        contactInformation: [{ required: true, message: '请输入联系方式', trigger: 'blur' }],
        a: [{ required: false, message: '', trigger: 'change', whitespace: false, min: 0 }]
      },
      passCheck: false,
      pass: false,
      pass2: false,
      pass3: false,
      item: undefined
    }
  },
  mounted() {
    this.item = this.$route.query
    if (this.$route.query.from !== undefined) {
      this.form.region = this.$route.query.from
    }
    console.log(this.$route.query.item)
    getfrom()
      .then(res => {
        this.diqu = res.result
      })
      .catch(e => {
        this.$message.warn('请求失败！')
      })
    if (this.$route.query.item) {
      this.$route.meta.title = '新增物资'
    } else {
      this.form.id = Number(this.$route.query.id)
      this.$route.meta.title = '编辑物资'
      this.AgencyDetails(this.$route.query)
    }
  },
  methods: {
    filterMultiDictText1(dictCode, text) {
      // console.log(dictCode,text)
      // if (!text && text !== 0) return
      let datas = getDictItemsFromCache(dictCode)
      // console.log(this.$filterDictText(datas, text))
      // return this.$filterMultiDictText(datas, text)
      // return this.$filterDictText(datas, text)
      return datas
    },
    AgencyDetails(val) {
      topXiangping(val.id)
        .then(response => {
          this.form.region = response.result.region
          this.form.contactInformation = response.result.contactInformation
          this.form.storageLocation = response.result.storageLocation
          this.form.latitude = response.result.latitude
          this.form.longitude = response.result.longitude
        })
        .catch(error => {
          console.log(error)
        })

      detailsList({ id: val.id })
        .then(response => {
          console.log(response)
          this.data = Object.keys(response.result).length > 0 && response.result ? response.result : []
          let c = 1
          for (let item of this.data) {
            item.index = c
            c++
          }
          console.log(this.data)
        })
        .catch(error => {
          console.log(error)
        })
    },
    // 输入模糊搜索信息列表
    onPisitionList(arr) {
      // console.log(arr)
      this.positionList = arr
    },
    onSearch(val) {
      // console.log(val)
      if (val == '') {
        return
      }
      this.$refs.mapDrawId.getPositionList(val)
    },
    onChange(val) {
      if (val != undefined) { }
      // console.log(val)
      this.form.storageLocation = val.address
      this.form.latitude = val.latitude
      this.form.longitude = val.longitude
    },

    uploads() {
      this.$router.push({
        path: '/listIndex'
      })
    },
    query() {
      this.submitForm()
      this.pass3 = true
      this.data.length === 0 ? this.pass2 = false : this.pass2 = true
      console.log(this.pass2)
      if (this.data.length !== 0) {
        for (let item of this.data) {
          delete item.updateBy
          delete item.updateTime
          for (let index in item) {
            console.log(item[index])
            if (item[index] === '' || item[index] === undefined) {
              console.log(item)
              this.$message.error('请检查物资基础信息第' + item.index + '行数据', 3)
              this.pass3 = false
              break
            }
          }
        }
      } else {
        this.$message.error('您此页的物资基础信息还没有填写完整,无法进行提交')
      }
      console.log(this.pass && this.pass2 && this.pass3)
      if (this.pass && this.pass2 && this.pass3) {
        if (this.$route.query.item) {
          if (!this.pass) {
            this.$message.error('您此页的数据还没有填写完整,无法进行提交')
          } else {
            let c = ''
            let arr = []
            for (let item of this.data) {
              arr.push({
                materialName: item.materialName,
                materialBrand: item.materialBrand,
                stock: item.stock,
                unit: item.unit
              })
            }
            let datas = {
              material: this.form,
              information: arr
            }
            console.log(datas)
            resCreate(datas)
              .then(res => {
                console.log(res)
                if (res.success) {
                  this.$message.success(res.message, 2)
                  for (let item of this.diqu) {
                    if (this.form.region === item.code) {
                      c = item.name
                    }
                  }
                  this.$router.push({
                    path: '/listIndex',
                    query: {
                      from: c
                    }
                  })
                } else {
                  this.$message.warn(res.message)
                }
              })
              .catch(e => {
                this.$message.warn('请求失败！')
              })
          }
        } else {
          this.visible = true
          // this.handleOk()
        }
      }

    },
    handleOk() {
      let arr = []
      for (let item of this.data) {
        arr.push({
          id: item.id,
          materialId: item.materialId,
          materialName: item.materialName,
          materialBrand: item.materialBrand,
          stock: Number(item.stock),
          unit: item.unit,
          modify: true
        })
      }
      let datas = {
        material: Object.assign({}, this.form, { id: this.$route.query.id }),
        information: arr
      }
      console.log(datas)
      updateWz(datas)
        .then(res => {
          // console.log(res)
          if (res.success) {
            this.$message.success(res.message, 2)
            this.visible = false
          } else {
            this.$message.warn(res.message, 2)
          }
          this.visible = false
        })
        .catch(error => {
          this.$message.warn('请求失败！')
          this.visible = false
        })
    },
    submitForm() {
      this.$refs.ruleForm.validate(valid => {
        // console.log(valid)
        // this.passCheck = valid
        this.$emit('passCheck', valid)
        this.pass = valid
        return valid
      })
    },
    handleAdd() {
      const { count, data } = this
      const newData = {
        id: count,
        key: count,
        index: count,
        materialName: ``,
        materialBrand: ``,
        stock: ``,
        editable: true,
        unit: ''
      }
      this.data = [...data, newData]
      console.log(this.data)
      this.count = count + 1
      // console.log('count:' + newData.id)
    },
    onDelete(id) {
      const dataSource = [...this.data]
      this.data = dataSource.filter(item => item.id !== id)
    },
    handleChange(value, id, column) {
      console.log(value, id, column)
      const newData = [...this.data]
      const target = newData.find(item => id === item.id)
      if (target) {
        target[column] = value
        this.data = newData
      }
    },
    edit(id) {
      const newData = [...this.data]
      newData.forEach((item, index) => {
        // console.log(item.id, id)
        if (item.id == id) {
          let oldItem = Object.assign({}, item) // 拷贝出新的对象
          this.oldData[index] = oldItem // 当前对象保存到数组，预备取消操作复原用
          if (item) {
            item.editable = true
            this.data = newData
          }
        }
      })
    },
    save(id) {
      // console.log(this.data)
      let newData = [...this.data]
      // let newCacheData = [...this.cacheData];
      let target = newData.find(item => id === item.id)
      // let targetCache = newCacheData.find(item => key === item.key);
      if (target) {
        delete target.editable
        this.data = newData
      }
    },
    cancel(id) {
      this.data.forEach((item, index) => {
        if (item.id == id) {
          item.editable = true
          const target = this.oldData[index]
          if (target != undefined) {
            this.$set(this.data, index, target)
          }
        }
      })
    },
    // resetForm() {
    //   this.$refs.ruleForm.resetFields();
    // },
    filterMultiDictText(dictCode, text) {
      if (!text && text !== 0) return
      let datas = getDictItemsFromCache(dictCode)
      // return this.$filterMultiDictText(datas, text)
      return this.$filterDictText(datas, text)
    }
  }
}
</script>

<style scoped>
.list {
  display: flex;
  flex-direction: column;
}

div /deep/.list label::before {
  display: inline-block;
  margin-right: 4px;
  color: #f5222d;
  font-size: 14px;
  font-family: SimSun, sans-serif;
  line-height: 1;
  content: '*';
}

div /deep/ .list .ant-form-item-control-wrapper {
  width: 100% !important;
}

div /deep/ .list .ant-col-2 {
  width: 100px !important;
}

.editable-row-operations a {
  margin-right: 8px;
}

div /deep/.ant-table-footer {
  display: flex;
  justify-content: center;
}
</style>
